<template>
	<view class="container-box">
		<view :style="'height:'+(custom.statusBar+custom.nvaMartom+custom.navHeight+20)+'rpx;position:fixed;top:0;background:rgba(0,0,0,0)'" class="custom">
			<view class="block custom-block" :style="'height:'+(custom.navHeight)+'rpx;width:100%;margin-top:'+(custom.statusBar+custom.nvaMartom)+'rpx;'">
				<view @click="backup" style="color:#fff" class="iconfont icon-zuojiantou backup-btn"></view>
				<image class="user-photo" mode="aspectFill" :src="roomData.faceUrl" style="margin-left: 20rpx;"></image>
				<view style="height:100%;color:#fff" class="title">{{roomData.realName}}</view>
				<view style="height:100%;color:#fff;margin: 0;font-size: 24rpx;" class="title">{{audience}}人在看</view>
				<view style="visibility: hidden;" class="iconfont icon-zuojiantou backup-btn"></view>
			</view>
		</view>
		<view class="push-block block" v-if="action==='anchor'">
			<live-pusher id="push" v-if="roomData" :url="roomData.sb" :beauty="pushConf.beauty"
				:whiteness="pushConf.whiteness" mode="HD" :device-position="pushConf['device-position']" :waiting-image="roomData.waitingImg"
				:remote-mirror="pushConf['remote-mirror']" :local-mirror="pushConf['local-mirror']"
				:enable-ans="pushConf['enable-ans']" :beauty-style="pushConf['beauty-style']"
				:enable-mic="pushConf['enable-mic']" @statechange="pushStateChange" @error="pushErr" class="media">
				<view style='position:absolute;bottom:0;height:10%;width:100%'>
					<view class="operate">
						<view @click="changeCamera" class='img-box'>
							<image class='img-view'
								:src="'../static/static/live/camera'+(pushConf['device-position']=='front'?'':'-gray')+'.png'"></image>
						</view>
						<view @click="getPosition" class='img-box'>
							<image class='img-view'
								:src="'../static/static/live/'+(showPosition?'position-show':'position')+'.png'">
							</image>
						</view>
						<view @click="setBeauty" class='img-box'>
							<image class='img-view'
								:src="'../static/static/live/'+(pushConf.beauty>0?'beauty':'beauty-dis')+'.png'"></image>
						</view>
					</view>
				</view>
			</live-pusher>
		</view>
		<view class="pull-block block" v-if="action==='audience'">
			<live-player id="pull" v-if="roomData" object-fit="fillCrop" :src="roomData.psb" @statechange="pullStateChange" @netstatus="pullNetChange" class="media">
				<view style='position:absolute;bottom:0;height:10%;width:100%'> 
					<view class="operate">
						<view @click="getPosition" class='img-box'>
							<image class='img-view'
								:src="'../static/static/live/'+(showPosition?'position-show':'position')+'.png'">
							</image>
						</view>
					</view>
				</view>
			</live-player>
		</view>
		<view v-show="showPosition" :class="showPosition?'shadow-block-show':'shadow-block-none'">
			<view class="position-block">
				<view class="title-block">
					<view class="show-title">直播带岗</view>
					<view @click="showPosition=false" class="close-text">关闭</view>
				</view>
				<view class="position-content">
					<block v-if="position.length>0">
						<block v-for="(item,index) in position" :key="item.id">
							<view class="enterprise-block" :class="item.show?'show':''">
								<view class="enterprise-item" @click="position[index].show=!position[index].show">
									<image mode="aspectFill" :src="item.logoUrl?item.logoUrl:imageUrl+'/job_hunting/job_detail/enterprise.jpg'"
										class="photo"></image>
									<view class="info-block">
										<view class="name">{{item.enterpriseName}}</view>
										<view class="count">{{`包含${item.jobPublishList.length}个岗位`}}</view>
									</view>
									<view :class="item.show?'icon-icon_xialaxuanze':'icon-gengduo1'" class="iconfont">
									</view>
								</view>
								<view v-for="(item2,index2) in item.jobPublishList" :key="item2.id" @click="navigatePos(item2.id)" class="position-item">
									<view class="job-title">{{item2.jobTitle}}</view>
									<view class="address">{{item2.jobAddress}}</view>
									<view class="wage">{{item2.minSalary}}-{{item2.maxSalary}}
										<view class="unit">元</view>
									</view>
								</view>
							</view>
						</block>
					</block>
					<view v-else class="empty">暂无数据</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import CustomNav from '../components/CustomNav/CustomNav.vue'
	import {push,pull} from '@/util/live.js';
	import {getCustomNavData} from '@/util/util.js'
	import {getLiveData as getLiveDataApi,getLivePostList,closeLive} from '@/api/live.js';
	export default {
		data() {
			return {
				action: 'audience',
				roomId: '',
				roomData: null,
				custom: null,
				pushConf: null,
				pushContext: null,
				pullConf: null,
				pullContext: null,
				showPosition:false,
				position:[],
				audience:0,
				restartPush:0,
				//socket示例
				socket:null,
				//定时器示例
				heartbeat:null,
				//是否初始化完成，完成后开始心跳
				loaded:false,
			}
		},
		components:{
			CustomNav
		},
		watch:{
			loaded:{
				handler(val){
					if(val){
						this.openWs();
					}
				}
			}
		},
		methods: {
			openWs(){
				let userId=(this.$store.getters.identity.toString()+this.$store.getters.user.id)*1;
				console.log(this.globalConfig.socketUrl+'/'+userId)
				this.socket=uni.connectSocket({
					url:this.globalConfig.socketUrl+'/'+userId,
					fail: () => {
						this.showToast('服务器连接失败')
					}
				})
				this.socket.onClose((e)=>{
					console.log('onClose',e);
					if(e.code!=1000){
						this.heartbeat&&clearInterval(this.heartbeat)
						this.openWs()
					}
				})
				this.socket.onError((e)=>{
					console.log('onError',e)
					this.heartbeat&&clearInterval(this.heartbeat)
					//this.openWs()
				})
				this.socket.onOpen(()=>{
					console.log('onOpen')
					this.socket.send({
						data:JSON.stringify({userId,action:this.action=='anchor'?1:2,roomId:this.roomData.roomNo,code:1}),
						complete:(e)=>{
							console.log('send',e)
						}
					})
					this.heartbeat=setInterval(()=>{
						this.socket.send({
							data:JSON.stringify({userId,action:this.action=='anchor'?1:2,roomId:this.roomData.roomNo,code:2}),
							complete:(e)=>{
								console.log('heartbeat',e)
							}
						})
					},10*1000)
				})
				this.socket.onMessage((e)=>{
					console.log('onMessage',e)
					const data=JSON.parse(e.data);
					this.audience=data.number;
					if(data.state==0){
						this.showToast('直播已结束,退出直播间',()=>{
							uni.navigateBack()
						})
					}
				})
			},
			navigatePos(id){
				if(this.action=='audience'){
					uni.navigateTo({
						url:`/page_other/job_hunting/job_detail/index?id=${id}&type=${this.$store.getters.identity==2?'hr':''}`
					})
				}
			},
			//显示带岗列表
			getPosition() {
				uni.showLoading({
					title: '加载中',
					mask: true
				})
				getLivePostList({
					roomNo: this.roomId
				}).then((res) => {
					let data = res??[];
					data.forEach((item, index) => {
						data[index].show = false;
					})
					this.position = data;
					this.showPosition = true;
				}).catch((res) => {
					this.showToast('加载失败，请重试');
				})
			},
			//切换美颜
			setBeauty(){
				this.pushConf.beauty=this.pushConf.beauty==0?5:0;
				this.pushConf.whiteness=this.pushConf.whiteness==0?5:0;
			},
			//切换摄像头
			changeCamera(){
				this.pushContext&&this.pushContext.switchCamera()
			},
			//返回按钮
			backup(){
				if(this.action==='anchor'){
					uni.showModal({
						title:'警告',
						content:'此操作会结束直播，确定吗',
						success(res) {
							if(res.confirm){
								uni.navigateBack()
							}
						}
					})
				}else{
					uni.navigateBack()
				}
			},
			getLiveData() {
				uni.showLoading({
					title: '获取信息中',
					mask: true,
				})
				getLiveDataApi({
					roomNo: this.roomId
				}).then((res) => {
					res.psb=res.psb.replace('m3u8','flv');
					this.roomData = res;
					this.audience=res.audience
					this.pushConf = JSON.parse(res.pushConf);
					uni.showLoading({
						title:'正在进入房间',
						mask:true,
					})
					uni.$TUIKit.joinGroup({
						groupID:res.roomNo
					}).then(()=>{
						uni.hideLoading()
						this.$nextTick(() => {
							if(this.action==='anchor'){
								this.startPush();
							}else{
								this.openWs()
								this.startPull()
							}
						})
					}).catch(()=>{
						uni.hideLoading();
						this.showToast('进入房间失败');
					})
				}).catch(() => {
					this.showToast('加载失败');
				})
			},
			startPush() {
				uni.showLoading({
					title:'启动推流中',
					mask:true
				})
				this.pushContext = uni.createLivePusherContext('push', this);
				this.pushContext.start();
				
			},
			pushErr(e) {
				uni.hideLoading();
				console.log(e)
				push.errCode[e.errCode]&&this.showToast(push.errCode[e.errCode]);
			},
			pushStateChange(e) {
				console.log('pushChange' + e.detail.code, push.code[e.detail.code]);
				
				switch (e.detail.code) {
					case 1002:
						this.showToast('开始直播!');
						if(this.restartPush==0){
							uni.hideLoading();
							this.loaded=true
						}
						break;
					case -1307:
						if(this.restartPush<3){
							this.showToast('重启推流',()=>{
								this.pushContext&&this.pushContext.start();
							})
							this.restartPush++
						}else{
							uni.showModal({
								title:'警告',
								content:'推流异常，直播结束',
								success:(e)=> {
									uni.navigateBack()
								}
							})
						}
						break;
						//rtmp推流服务异常
					case 3001:
					case 3002:
					case 3003:
					case 3005:
						this.showToast(push.code[e.detail.code])
						break;
					case 3004:
						uni.showModal({
							title:'警告',
							content:push.code[e.detail.code],
							success:(e)=> {
								uni.navigateBack()
							}
						})
						break;
				}
			},
			startPull() {
				this.pullContext = uni.createLivePlayerContext('pull', this);
				this.pullContext.play();
			},
			pullStateChange(e){
				console.log(e)
			},
			pullNetChange(e){
				console.log(e)
			},
		},
		onLoad(param) {
			this.custom = getCustomNavData()
			if (!param.roomId) {
				this.showToast('房间号错误', () => {
					uni.navigateBack();
				})
				return;
			}
			this.roomId = param.roomId;
			this.action = param?.action ?? 'audience';
			this.imageUrl=this.globalConfig.imageUrl
			this.getLiveData();
		},
		onShow() {
			uni.setKeepScreenOn({
				keepScreenOn: true
			})
		},
		onUnload() {
			uni.setKeepScreenOn({
				keepScreenOn: false
			})
			if(this.action==='anchor'){
				uni.$TUIKit.dismissGroup(this.roomId)
				closeLive({roomNo: this.roomId})
				this.pushContext=null;
				this.roomData=null;
			}else{
				uni.$TUIKit.quitGroup(this.roomId)
			}
			this.socket&&this.socket.close({code:1000,reason:'close'});
			this.heartbeat&&clearInterval(this.heartbeat)
		}
	}
</script>
<style lang="scss" scoped>
	.operate {
		position: absolute;
		margin-left: auto;
		margin-right: auto;
		right: 0;
		left: 0;
		bottom: 3vh;
		width: fit-content;
		height: 50px;
		text-align: center;
	}
	.img-box {
		position: relative;
		display: inline-block;
		height: 50px;
		margin: 0 20px;
		vertical-align: middle;
		text-align: center;
		z-index: 999999;
	}
	
	.img-view {
		position: relative;
		display: block;
		width: 50px;
		height: 50px;
	}
	.custom {
		z-index: 999999;
		width: 100%;
		transition: all .3s ease;
		.custom-block {
			display: flex;
			align-items: center;

			.iconfont.backup-btn {
				display: flex;
				align-items: center;
				flex-grow: 0;
				margin-left: 20rpx;
				color: #fff;
				font-size: 36rpx;
				transition: all .3s ease;
			}

			.title {
				display: flex;
				justify-content: flex-start;
				align-items: center;
				margin: 0 20rpx;
				color: #fff;
				transition: all .3s ease;
			}

			.user-photo {
				width: 60rpx;
				height: 60rpx;
				border-radius: 50%;
				flex-grow: 0;
			}
		}
	}

	.block {
		width: 100vw;
		height: 100vh;
		position: fixed;
		top: 0%;
		left: 0;

		.media {
			width: 100%;
			height: 100%;
		}
	}
	.shadow-block-show{
		z-index: 9999999;
		position: fixed;
		width: 100vw;
		height:100vh;
		top: 0;
		background: rgba(0, 0, 0, 0.5);
		.position-block{
			position: absolute;
			width: 100%;
			height: 60%;
			bottom: 0;
			background: #fff;
			z-index: 99999999;
			border-radius: 20rpx 20rpx 0 0;
			.title-block{
				padding: 0 30rpx;
				display: flex;
				flex-direction: row;
				align-items: center;
				height: 80rpx;
				border-bottom: 1px solid #efefef;
				.show-title{
					flex-grow: 1;
				}
				.close-text{
					color: #ff7626;
					flex-grow: 0;
				}
			}
			.position-content{
				display: flex;
				flex-direction: column;
				padding:0 30rpx;
				overflow-y: scroll;
				height: calc(100% - 80rpx);
				.enterprise-block{
					height: 201rpx;
					padding: 30rpx 0;
					border-bottom: 1px solid #efefef;
					display: flex;
					flex-direction: column;
					overflow: hidden;
					flex: none;
					.enterprise-item {
						border-radius: 10rpx;
						padding: 20rpx;
						display: flex;
						flex-direction: row;
						height: 140rpx;
						.photo {
							width: 100rpx;
							height: 100rpx;
							border-radius: 16rpx;
							background: #f0f0f0;
							margin-right: 20rpx;
						}
					
						.info-block {
							width: calc(100% - 120rpx);
							height: 100rpx;
							display: flex;
							flex-direction: column;
							justify-content: space-between;
					
							.name {
								font-weight: bold;
								font-size: 30rpx;
							}
					
							.count {
								font-size: 28rpx;
								color: #fe7725;
							}
						}
						.iconfont{
							width: 30rpx;
							height: 100%;
							display: flex;
							align-items: center;
						}
					}
					.position-item {
						width: 100%;
						display: flex;
						flex-direction: column;
						padding: 30rpx;
						.job-title {
							font-size: 32rpx;
							font-weight: bold;
						}
					
						.address {
							font-size: 28rpx;
							color: #999;
							margin-top: 16rpx;
						}
					
						.job-title,
						.address,
						.wage {
							overflow: hidden;
							white-space: nowrap;
							text-overflow: ellipsis;
						}
						.wage {
							color: #FE7526;
							font-size: 36rpx;
							font-weight: bold;
							display: flex;
							flex-direction: row;
							align-items: center;
							margin-top: 16rpx;
							.unit {
								font-size: 28rpx;
								font-weight: normal;
							}
						}
					}
				}
				.enterprise-block:last-child{
					border-bottom: 1px solid rgba(0,0,0,0);
				}
				.enterprise-block.show{
					height: auto;
					overflow: visible;
				}
			}
			
		}
		
	}
</style>
